/**********************************************
** @Des: This file ...
** @Author: xiaomeng79
** @Date:   17-11-16 下午6:10
***********************************************/
package libs

import (
	"crypto/md5"
	"fmt"
	"time"
	"math/rand"
	"strings"
)

/**
MD5加密
 */
func Md5(buf []byte) string {
	hash := md5.New()
	hash.Write(buf)
	return fmt.Sprintf("%x", hash.Sum(nil))
}

/**
生成密码
 */
func Password(len int, pwdO string) (pwd string, salt string) {
	salt = GetRandomString(len)
	defaultPwd := "123456"
	if pwdO != "" {
		defaultPwd = pwdO
	}
	pwd = Md5([]byte(defaultPwd + salt))
	return pwd, salt
}

/**
生成随机字符串
 */
func GetRandomString(lens int) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < lens; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

/**
interface to string
 */
func InterfaceToString(i interface{}) string {
	if s,ok := i.(string); ok {
		return s
	}
	return ""
}

/**
字符串是否在数组中
 */
func Str_In_Array(s string, arr []string) bool {
	for _,v := range arr {
		if  v == s {
			return true
		}
	}
	return false
}

/**
过滤字符串
 */
func FilterStr(str string) string {
	return strings.TrimSpace(str)
}